/*
 * Copyright 2011-2012 Redia A/S
 * 
 * This file is part of Indhold+ for Android.
 *
 *  Redia Library App for Android is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Redia Library App for Android is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License
 *  along with Redia Library App for Android.  If not, see <http://www.gnu.org/licenses/>.
 */
package dk.redia.digiform;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import android.app.Activity;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.media.MediaPlayer;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.Layout;
import android.text.method.ScrollingMovementMethod;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import dk.redia.digiform.utils.NfcScanner;
import dk.redia.digiform.utils.RFIDScannerThread;
import dk.redia.digiform.utils.ScanResultListener;
import dk.redia.digiform.utils.usbBasedRFIDScannerThread;

import dk.redia.lib.log.Log;
import dk.redia.lib.utils.AppApplication;
import dk.redia.lib.utils.AppConfiguration;
import dk.redia.lib.utils.VersionUtils;

import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialProber;

public class DigiformActivity extends Activity implements ScanResultListener {
	/** Called when the activity is first created. */
	public enum ScannerMethod {
		 Bluetooth, BuildInNFC, ExternalUSBBasedRFIDreader;
	}
	
	private static final String logTag = "DigiformActivity";
	private BluetoothAdapter btAdapter;
	private Set<BluetoothDevice> btDevices;
	private BluetoothDevice btRFIDScannerDevice;
	private BluetoothBroadcastReceiver broadcastReceiver;
//	private String btDeviceName = "BTRFID"; // Test device
	private String btDeviceName = "BT_RFID";
//	private Timer scanTimer;
	private Timer scannerConnectTimer;
	private int scanIntervalMs = 2000;
	private BluetoothSocket btSocket;
//	private TimerTask scanTimerTask;
	private TimerTask scannerConnectTimerTask;
	private MediaPlayer mediaPlayer;
//	private boolean scanning = false;
	private boolean scannerConnected = false;
	private boolean btDiscoveryInProgress = false;
//	private String currentTagId;
	private ImageView bluetoothLogoImageView;
	private TextView logTextView;
	private ProgressBar pb;
	private RFIDScannerThread scannerThread;
	private boolean isPaused;
	
	
	private ScannerMethod scannerMethod = ScannerMethod.ExternalUSBBasedRFIDreader;
	private NfcAdapter mAdapter;
	private NfcScanner scanner;
	private usbBasedRFIDScannerThread usbScannerThread;
	
	private void loadResourceData(String resourceId) {
//		pb.setVisibility(View.VISIBLE);
		Intent intent = new Intent(DigiformActivity.this, ResourceOverviewActivity.class);
		intent.putExtra(ResourceOverviewActivity.EXTRA_RESOURCE_ID, resourceId);
		startActivity(intent);	
		overridePendingTransition(R.anim.fadein, R.anim.fadeout);
	}
	
	public void onPause() {
		super.onPause();
		Log.d(logTag, "Pausing DigiformActivity");
		isPaused = true;
//		if (scannerThread!=null) {
		//	scannerThread.removeListener(this);
//		}
	}
	
	public void onResume() {
		super.onResume();
		Log.d(logTag, "Resuming DigiformActivity");
		isPaused = false;
		
		if(scannerMethod == ScannerMethod.BuildInNFC) {
			PendingIntent intent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
			mAdapter.enableForegroundDispatch(this, intent, null, null);
		}
//		if (scannerThread!=null) {
//			scannerThread.addListener(this);
//		}else{
//			scannerConnected = false;
//		}
	}
	
	public void onNewIntent(Intent intent) {
		if(NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
			Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
			scanner.readNfcVTag(tag);
		}
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		VersionUtils.setVersion("12.08.29001");
		VersionUtils.setVersionNickName("Digiform");
		AppApplication.setApplicationContext(getApplicationContext());
		AppConfiguration.setAppConfiguration(new AppConfiguration() {
			
			private boolean productionMode = true;
			
			@Override
			public void setUiLanguage(String language) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void setContentLanguage(String language) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public String getUiLanguage() {
				// TODO Auto-generated method stub
				return null;
			}
			
			@Override
			public String getInfoGalleriXmlRpcUrl() {
				// TODO Auto-generated method stub
				return null;
			}
			
			@Override
			public int getInfoGalleriModelRefreshInterval() {
				// TODO Auto-generated method stub
				return 0;
			}
			
			@Override
			public String getGalleryId() {
				// TODO Auto-generated method stub
				return null;
			}
			
			@Override
			public String getCustomerId() {
				// TODO Auto-generated method stub
				return null;
			}
			
			@Override
			public String getContentLanguage() {
				// TODO Auto-generated method stub
				return null;
			}
			
			@Override
			public String getApiKey() {
				// TODO Auto-generated method stub
				return null;
			}

			//@Override
			public boolean getProductionMode() {				
				return productionMode;
			}

			//@Override
			public void setProductionMode(boolean productionMode) {
				this.productionMode = productionMode;
				
			}
		});
	    // Ensure that screen doesn't get turned off
	    getWindow().addFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		// For use later, we create a self referencing
		// timer task.
		/*
		scanTimerTask = new TimerTask() {

			@Override
			public void run() {				
				runOnUiThread(new Runnable() {					
					public void run() {
						
						try {
							if (scanning) {
								uiLog(logTag, "Scan already in progress");
								return;
							}
							if (!scannerConnected) {
								uiLog(logTag, "Scanner doesn't appear to be connected");
								return;
							}
							String data = scan();
							if (data!=null) {
								mediaPlayer.start();
								uiLog(logTag, data);
//								if (data.length()<10) {
//									uiLog(logTag, "Tag payload doesn't appear to contain a valid resource id");
//									return;
//								}
								Pattern p = Pattern.compile(".*?([0-9]+).*?");
								Matcher m = p.matcher(data);
								String resourceId = null;
								if (m.matches()) {
									resourceId = m.group(1);
								} else {
									uiLog(logTag, "Unable to parse RFID payload");
									return;
								}
								loadResourceData(resourceId);
							} else {
								uiLog(logTag, "Scanning yielded no results");
							}
						} catch (IOException e) {
							uiLog(logTag, "An error occurred during scanning: " + e.getMessage());
							scannerConnected = false;
							bluetoothLogoImageView.setVisibility(View.INVISIBLE);
							uiLog(logTag, "Marking scanner as disconnected");
							btDevices.clear();
							btRFIDScannerDevice = null;
							if (btSocket!=null) {
								try {
									btSocket.close();
								} catch (IOException e1) {
									// TODO Auto-generated catch block
									e1.printStackTrace();
								}
								btSocket = null;
							}
						}
					}
				});
			}
		};
		*/
	    pb = (ProgressBar)findViewById(R.id.frontPageProgressBar);
		
	    switch (scannerMethod) {
	      case Bluetooth:
				bluetoothLogoImageView = (ImageView)findViewById(R.id.bluetoothLogoImageView);
				logTextView = (TextView)findViewById(R.id.frontpageLogTextView);
				logTextView.setMovementMethod(new ScrollingMovementMethod());
				mediaPlayer = MediaPlayer.create(this, Settings.System.DEFAULT_NOTIFICATION_URI);
//				scanTimer = new Timer();
				scannerConnectTimer = new Timer();
				btDevices = new HashSet<BluetoothDevice>();
		
				broadcastReceiver = new BluetoothBroadcastReceiver();
		
				registerReceiver(broadcastReceiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED));
				registerReceiver(broadcastReceiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED));        
				registerReceiver(broadcastReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED)); 
				registerReceiver(broadcastReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND)); 
		
				btAdapter = BluetoothAdapter.getDefaultAdapter();        
		
				if (btAdapter!=null) {
					
					if (btAdapter.getState()==BluetoothAdapter.STATE_ON) {
						uiLog(logTag, "Bluetooth adapter is ON. Starting discovery");
						btDiscoveryInProgress = true;
						btAdapter.startDiscovery();
					} else {
						uiLog(logTag, "Bluetooth adapter is OFF. Turning on.");
						btAdapter.enable();
					}
			
					scannerConnectTimerTask = new TimerTask() {
			
						@Override
						public void run() {
							runOnUiThread(new Runnable() {
			
								public void run() {
									uiLog(logTag, "Checking if scanner is connected");
									if (btDiscoveryInProgress) {
										return;
									}
									if (scannerConnected) {
		//								if(scannerThread == null){
		//									scannerConnected = false;
		//								}
										return;
									}
									if (btAdapter.getState()==BluetoothAdapter.STATE_ON) {
										uiLog(logTag, "Bluetooth adapter is ON. Starting discovery");
										btDiscoveryInProgress = true;
										btAdapter.startDiscovery();
									} else {
										uiLog(logTag, "Bluetooth adapter is OFF. Turning on.");
										btAdapter.enable();
									}
								}
							});
						}
					};
		//			scanTimer.scheduleAtFixedRate(scanTimerTask, 0, scanIntervalMs);
					scannerConnectTimer.scheduleAtFixedRate(scannerConnectTimerTask, scanIntervalMs, scanIntervalMs*10);
				} else {
					uiLog(logTag, "No bluetooth adapter detected");
				}
	    	  break;
	    	  
	      case BuildInNFC:
				pb.setVisibility(View.INVISIBLE);
				mAdapter = NfcAdapter.getDefaultAdapter(this);
				scanner = new NfcScanner(this);
				scanner.addListener(this);
	    	  break;
	    	  
	      case ExternalUSBBasedRFIDreader:
				// Get UsbManager from Android.
				UsbManager mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);

			    mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
			    mUsbManager.getDeviceList();  
			    HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList(); 
			    Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
			    
			    log("Number of USB devices found: " + deviceList.size());

			    log(mUsbManager.toString());
			    		    
			    UsbDevice device=null;       
			    while(deviceIterator.hasNext()){
			      device = deviceIterator.next();  
			      log( device.getDeviceName()+" vendorid: "+device.getVendorId()+"  productid: "+device.getProductId() );
			    }			
				
			    // TODO Handle the asynchronous permission response and act accordingly  
			    PendingIntent mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
			    IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
			    registerReceiver(mUsbReceiver, filter);		    
			    		    
			    mUsbManager.requestPermission(device, mPermissionIntent);		    
			    
				// Find the first available device.
				UsbSerialDriver driver = UsbSerialProber.findFirstDevice(mUsbManager);
				
				if (driver != null) {
					log("UsbSerialDriver is sane and device found!");
					
					  try {
	 
					    usbScannerThread = new usbBasedRFIDScannerThread(driver);
					    usbScannerThread.addListener(DigiformActivity.this);
					    usbScannerThread.start();
				
					  } catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					  } finally {
					  } 				
	/*
					  try {
						driver.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	*/
			  }
	    	  break;
	      default:
			    log("No scanners choosen!");
	    	  break;
	    }
} 

	public void onDestroy() {
		super.onDestroy();
//		scanTimer.cancel();
		//scannerConnectTimer.cancel();
		try {
			if (btSocket!=null) {
				btSocket.close();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (btAdapter!=null) {
			btAdapter.disable();
		}
		//unregisterReceiver(broadcastReceiver);
	}
/*
	private String readResponse(InputStream is) {
		byte previous = '\0';
		byte[] buffer = new byte[1];
		int bytesRead;
		String result = new String();
		//boolean responseRead = false;
		try {
			//int bytesRead = 0;
			uiLog(logTag, "About to read single byte");
			while ((bytesRead = is.read(buffer, 0, buffer.length))>=0) {
				//uiLog(logTag, "Read " + bytesRead + " bytes");
				if (buffer[0]=='\n' && previous=='\r') {
					uiLog(logTag, "Found end of response");
					return result;
				}
				if (buffer[0]!='\n' && buffer[0]!='\r') {
					result += (char)buffer[0];
				}
				previous = buffer[0];
			}
			return result;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	*/
/*
	private String fromHex(String str) {
		StringBuilder ascii = new StringBuilder();
		for (int i = 0; i < str.length(); i += 2) {
			String part = str.substring(i, i + 2);
			if (!part.equals("00")) {
				ascii.append((char)Integer.parseInt(part, 16));
			}
		}
		return ascii.toString();
	}
*/
	/*
	private String scan() throws IOException {

		OutputStream os =  btSocket.getOutputStream();
		InputStream is = btSocket.getInputStream();
		os.write("\r001400\r".getBytes());
		try { Thread.sleep(1000); } catch (InterruptedException e) {}
		uiLog(logTag, "Wrote command to scanner");
		String response = readResponse(is);
		//char c = (char)is.read();
		if (response==null) {
			throw new IOException("Unable to read from scanner. It may have disconnected");
		}
		if (response.length()<4) {
			uiLog(logTag, "Failed to read tag id from scanner");
			// Remember to unset the current tag id
			currentTagId = null;
			return null;
		}
		String tid = response.substring(4);						
		uiLog(logTag, "Found tag " + tid);
		if (currentTagId!=null && currentTagId.equals(tid)) {
			Log.d(logTag, "We already found this tag, so no need to announce it again");
			return null;
		}
		currentTagId = tid;
		try { Thread.sleep(1000); } catch (InterruptedException e) {}
		String cmd = "\r402401" + tid + "0010\r";
		os.write(cmd.getBytes());
		try { Thread.sleep(1000); } catch (InterruptedException e) {}
		String data = readResponse(is);
		if (data.length()<4) {
			uiLog(logTag, "Failed to read data from RFID tag");
			return null;
		}
		data = data.substring(2);
		uiLog(logTag, data);
		uiLog(logTag, fromHex(data));

		return fromHex(data);
	}
	*/
	
	/*private class OnBootBroadcastReceiver extends BroadcastReceiver {
		
		public void onReceive(Context context, Intent intent) {
			Intent i = new Intent(context, DigiformActivity.class);
			context.startActivity(i);
		}
	}*/

	private static final String ACTION_USB_PERMISSION =
		    "com.android.example.USB_PERMISSION";
	
	private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {

		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
		    if (ACTION_USB_PERMISSION.equals(action)) {
		    	synchronized (this) {
		    		UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);

		            if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
		            	if(device != null){
		            		//call method to set up device communication
		                    log("Hello from mUsbReceiver!");
		                }
		            } 
		            else {
		            	log("permission denied for device " + device);
		            }
		        }
		    }
		}
	};	
	
	private class BluetoothBroadcastReceiver extends BroadcastReceiver {

		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {				
				btDiscoveryInProgress = false;

				btRFIDScannerDevice = null;
				uiLog(logTag, "Finished bluetooth discovery");
				for (BluetoothDevice btDevice : btDevices) {
					if (btDevice!=null) {
						if (btDevice.getName()!=null) {
							if (btDevice.getName().equals(btDeviceName)) {
								uiLog(logTag, "Found BTRFID device in range");
								btRFIDScannerDevice = btDevice;
								break;
							}
						}
					}
				}
				if (btRFIDScannerDevice==null) {
					uiLog(logTag, "Didn't find a valid BTRFID device in range");
				}
				if (btRFIDScannerDevice!=null) {
					try {	
						btAdapter.cancelDiscovery();
						
						if (Build.VERSION.SDK_INT>=14) {
							// We are on android 4.x so this works
							btSocket = btRFIDScannerDevice.createInsecureRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
						} else {
							// We are on an older version of android, so we need to do this
							try {
								Method m = btRFIDScannerDevice.getClass().getMethod("createInsecureRfcommSocket", new Class[] {int.class});
								btSocket = (BluetoothSocket) m.invoke(btRFIDScannerDevice, 1);
				 			} catch (SecurityException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
								return;
							} catch (NoSuchMethodException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
								return;
							} catch (IllegalArgumentException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
								return;
							} catch (IllegalAccessException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
								return;
							} catch (InvocationTargetException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
								return;
							}
						}


						
						 
						if (btSocket==null) {
							uiLog(logTag, "Failed to create bluetooth socket");
							return;
						}
						uiLog(logTag, "Created bluetooth socket");
						// On galaxy tab 2 this may throw a null pointer exception
						try {
							btSocket.connect();
						} catch (Exception e) {
							Log.e(logTag, "Failed to establish bluetooth connection, although socket was successfully created: "+e.getMessage());
							scannerConnected = false;
							return;
						}
						uiLog(logTag, "Connected bluetooth socket");
						scannerConnected = true;
						scannerThread = new RFIDScannerThread(btSocket);
						scannerThread.addListener(DigiformActivity.this);
						scannerThread.start();
						bluetoothLogoImageView.setVisibility(View.VISIBLE);
						//try { Thread.sleep(1000); } catch (InterruptedException e) {}
						// Everything needed is in the background, so hide this label
						logTextView.setVisibility(View.INVISIBLE);
						pb.setVisibility(View.INVISIBLE);
						return;
						/*
						String response = "";
//						String cmd = "\r\r\r001401\r\r\r";
						String cmd = "\r\r\r\r\r\r";
//						String cmd = "\r402401E"
						//byte[] buffer = new byte[21];
						uiLog(logTag, "Writing command");
						btSocket.getOutputStream().write(cmd.getBytes(), 0, cmd.length());
						btSocket.getOutputStream().flush();
						btSocket.close();
						uiLog(logTag, "Waiting for response");
//						try {
//							Thread.sleep(1000, 0);
//						} catch (InterruptedException e) {
//							// TODO Auto-generated catch block
//							e.printStackTrace();
//						}

						InputStream is = btSocket.getInputStream();
						uiLog(logTag, "Reading");
						//is.read(buffer, 0, 1);
						is.read();
//						String response = new String(buffer);
						uiLog(logTag, "Reading response");
//						String response = readResponse(btSocket);

						// Buffer contains something like this:
						//\n1401E0040150113F0E78	
						//uiLog(logTag, "Read: " + response);
						if (response==null || response.length()<=4) {
							Log.e(logTag, "Failed to read RFID tag id");
							return;
						}
						String tid = response.substring(4);
						//String tid = ""; // Hold the tag id
						uiLog(logTag, "Found tag id: " + tid);
						cmd = "\r402401" + tid + "0010\r";
						uiLog(logTag, "Writing command");
//						buffer = new byte[1 + 2 + (0x10 * 8)];  // Line feed + response code + data
						btSocket.getOutputStream().write(cmd.getBytes(), 0, cmd.length());
						btSocket.getOutputStream().flush();
						try {
							Thread.sleep(5000, 0);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
//						btSocket.getInputStream().read(buffer, 0, 1 + 2 + (0x10 * 8)); // Line feed + response code + data
//						response = new String(buffer);
						response = readResponse(btSocket);
						uiLog(logTag, response);
						String tagData = fromHex(response);
						uiLog(logTag, tagData);
						 */

					} catch (IOException e) {
						uiLog(logTag, "Failed to create bluetooth socket:  " + e.getMessage());			
						return;
					} 
				}
			} else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_STARTED)) {
				uiLog(logTag, "Started bluetooth discovery");
			} else if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
				uiLog(logTag, "Bluetooth radio changed state");
				if (btAdapter.getState()==BluetoothAdapter.STATE_ON) {
					uiLog(logTag, "Bluetooth adapter is ON. Starting discovery");
					btAdapter.startDiscovery();
					btDiscoveryInProgress = true;
				}
			} else if (action.equals(BluetoothDevice.ACTION_FOUND)) {
				uiLog(logTag, "Bluetooth device found");
				BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				btDevices.add(device);
			} else {
				uiLog(logTag, "Unknown action: " + action);
			}
		}
	}

	private void uiLog(String logTag, String msg) {
		TextView tv = (TextView)findViewById(R.id.frontpageLogTextView);
		if (tv!=null) {
			tv.append("[" + new Date().toString() + "] ");
			tv.append(msg);
			tv.append("\n");
			Layout tvLayout = tv.getLayout();
			if (tvLayout!=null) {
				final int scrollAmount = tv.getLayout().getLineTop(tv.getLineCount())-tv.getHeight();
				if (scrollAmount>0) {
					tv.scrollTo(0, scrollAmount);
				}
			}
		}
		Log.d(logTag, msg);
	}

	public void scanned(final String resourceId) {
		switch (scannerMethod) {
		case Bluetooth:
			break;
		case BuildInNFC:
			loadResourceData(resourceId);
			break;
		case ExternalUSBBasedRFIDreader:
			loadResourceData(resourceId);
			break;
		default:
			if(!isPaused){
				runOnUiThread(new Runnable() {
					public void run() {
						mediaPlayer.start();
						Log.d(logTag, "Scanned resource with id " + resourceId);
						loadResourceData(resourceId);
					}
				});
			}
		}
	}

	public void disconnected() {
		if (scannerMethod == ScannerMethod.BuildInNFC) {
			mAdapter.disableForegroundDispatch(this);
		} else {
			runOnUiThread(new Runnable() {
				
				public void run() {
					scannerConnected = false;
					bluetoothLogoImageView.setVisibility(View.INVISIBLE);
					Log.d(logTag, "Scanner disconnected");
				}
			});
		}
	}

	public void log(final String message) {
		runOnUiThread(new Runnable() {
			
			public void run() {
				Log.d(RFIDScannerThread.logTag, message);
			}
		});

	}

	@Override
	public void error() {
		// TODO Auto-generated method stub
		LayoutInflater inflater = getLayoutInflater();
		View layout = inflater.inflate(R.layout.toast_material_removed_too_fast,
		                               (ViewGroup) findViewById(R.id.toast_material_removed_too_fast));
		Toast toast = new Toast(getApplicationContext());
		toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
		toast.setDuration(Toast.LENGTH_LONG);
		toast.setView(layout);
		//toast.show();
		for (int i=0; i < 2; i++)
		{
		      toast.show();
		}
	}

}
